<!-- 添加文章页 -->
<script>
    import { onMount } from "svelte";
    import useCurrentRoute from "@easyroute/svelte/useCurrentRoute";
    import {
        Row,
        Col,
        Select,
        Button,
        TextField,
        MaterialApp,
    } from "svelte-materialify";

    import { Editor } from "bytemd";
    import gfm from "@bytemd/plugin-gfm";
    import highlight from "@bytemd/plugin-highlight";
    import breaks from "@bytemd/plugin-breaks";
    import frontmatter from "@bytemd/plugin-frontmatter";
    import mediumZoom from "@bytemd/plugin-medium-zoom";
    import mermaid from "@bytemd/plugin-mermaid";
    import mermaidLocale from "@bytemd/plugin-mermaid/locales/zh_Hans.json";
    import zhHans from "bytemd/locales/zh_Hans.json";
    import { Snackbar, Button as MuiButton } from "svelte-mui/src";

    // 引入基础css
    import "bytemd/dist/index.css";
    // 引入高亮css
    import "highlight.js/styles/vs.css";
    import "github-markdown-css";

    import {
        getArticleInfo,
        saveArticle,
        editArticle,
    } from "../../api/article";
    import { getCateList } from "../../api/category";
    import router from "../../routes";

    // 获取当前路由信息
    const currentRoute = useCurrentRoute();
    // console.log($currentRoute);
    console.log($currentRoute.params.id);
    let editArtId = $currentRoute.params.id;

    let errAlertVisible = false;
    let errAlertMsg = "error";
    let okAlertVisible = false;
    let okAlertMsg = "success";

    // 全部分类（选择框使用）
    let cateListItems = [];
    // // 全部分类
    // let cateList = [];

    // 分类id(选中的分类)
    let cateSelectedId = 0;

    // 文章标题
    let title = "";
    // // 分类id
    // let cateid = 0;
    // 文章内容
    let content = "";

    // markdown编辑器模式
    let mode = "auto";

    // markdown编辑器插件
    const plugins = [
        gfm(),
        highlight(),
        breaks(),
        mermaid({ locale: mermaidLocale }),
        frontmatter(),
        mediumZoom(),
    ];

    // 标题验证规则
    const titleRules = [(v) => !!v || "Required"];

    // 生命周期时间，挂载完毕
    onMount(async () => {
        getAllCate();

        if (editArtId && editArtId > 0) {
            getArtInfo(editArtId);
        }
    });

    // 获取分类信息
    const getAllCate = () => {
        getCateList().then((res) => {
            if (res.data.code != 200) {
                console.log(res.data.msg);
                errAlertMsg = res.data.msg;
                errAlertVisible = true;
                return;
            }

            let data = res.data.data;
            // cateList = data;
            cateListItems = data.map((v) => {
                return {
                    name: v.name,
                    value: v.id,
                };
            });
        });
    };

    // 获取待编辑文章信息
    const getArtInfo = (id) => {
        getArticleInfo(id)
            .then((res) => {
                if (res.data.code != 200) {
                    console.log(res.data.msg);
                    errAlertMsg = res.data.msg;
                    errAlertVisible = true;
                    return;
                }

                title = res.data.data.title;
                cateSelectedId = res.data.data.classId;
                content = res.data.data.content;
            })
            .catch((err) => {
                console.log(err);
            });
    };

    // 文章内容文字改变触发函数
    const articleContentChange = (e) => {
        content = e.detail.value;
    };

    // 按钮提交
    const btnSubmit = () => {
        // console.log("提交保存文章");
        // console.log(cateSelectedId);

        if (editArtId && editArtId > 0) {
            let art = {
                id: Number(editArtId),
                title: title,
                classId: cateSelectedId,
                content: content,
            };

            // 编辑文章
            editArticle(art)
                .then((res) => {
                    if (res.data.code != 200) {
                        console.log(res.data.msg);
                        errAlertMsg = res.data.msg;
                        errAlertVisible = true;
                        return;
                    }

                    okAlertMsg = "修改文章成功";
                    okAlertVisible = true;

                    router.push("/admin/artList");
                })
                .catch((err) => {
                    console.log(err);
                });
        } else {
            // 新增文章
            let art = {
                title: title,
                classId: cateSelectedId,
                content: content,
            };
            saveArticle(art)
                .then((res) => {
                    if (res.data.code != 200) {
                        console.log(res.data.msg);
                        errAlertMsg = res.data.msg;
                        errAlertVisible = true;
                        return;
                    }

                    okAlertMsg = "新增文章成功";
                    okAlertVisible = true;

                    router.push("/admin/artList");
                })
                .catch((err) => {
                    console.log(err);
                });
        }
    };
</script>

<Snackbar
    color="#f56c6c"
    bg="#fef0f0"
    bind:visible={errAlertVisible}
    timeout={1}
    style="height: 30px; border-radius: 4px;"
>
    {errAlertMsg}
    <span slot="action">
        <MuiButton
            color="#a8abb2"
            on:click={() => {
                errAlertVisible = false;
            }}>✕</MuiButton
        >
    </span>
</Snackbar>
<Snackbar
    color="#67c23a"
    bg="#f0f9eb"
    bind:visible={okAlertVisible}
    timeout={1}
    style="height: 30px; border-radius: 4px;"
>
    {okAlertMsg}
    <span slot="action">
        <MuiButton
            color="#a8abb2"
            on:click={() => {
                okAlertVisible = false;
            }}>✕</MuiButton
        >
    </span>
</Snackbar>

<p style="color: #03a9f4;">添加文章</p>

<div style=" margin: 10px 5px;">
    <MaterialApp>
        <Row style="width: 98%;margin: 0 auto;">
            <Col>
                <!-- 标题 -->
                <Row style="margin-bottom: 30px;">
                    <TextField clearable bind:value={title} rules={titleRules}
                        >标题</TextField
                    >
                </Row>

                <!-- 选择分类 -->
                <Row style="margin-bottom: 30px;">
                    <Select items={cateListItems} bind:value={cateSelectedId}
                        >分类</Select
                    >
                </Row>

                <!-- 编辑器 -->
                <Row style="margin-bottom: 25px;">
                    <Editor
                        class="mdeditor"
                        value={content}
                        {mode}
                        {plugins}
                        placeholder={"请输入文章内容"}
                        locale={zhHans}
                        on:change={articleContentChange}
                    />
                </Row>

                <!-- 提交按钮 -->
                <Row>
                    <Button class="blue white-text" on:click={btnSubmit}
                        >提交</Button
                    >
                </Row>
            </Col>
        </Row>
    </MaterialApp>
</div>

<style>
    :global(.s-select .s-menu) {
        z-index: 100 !important;
    }

    :global(.bytemd) {
        width: 100%;
        height: 650px;
        z-index: 99;
    }

    :global(.medium-zoom-overlay) {
        z-index: 100;
    }

    :global(.medium-zoom-image--opened) {
        z-index: 101;
    }
</style>
